package com.chen.blue.utils;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created By CLT On 2023/10/30.
 */
@SuppressWarnings("all")
@Slf4j
public class ServletUtil {

    /**
     * 响应文本
     *
     * @param renderStr
     * @param response
     */
    public static void renderString(String renderStr, HttpServletResponse response) {

        String content = JSONUtil.toJsonStr(renderStr);
        cn.hutool.extra.servlet.ServletUtil.write(response, content, MediaType.APPLICATION_JSON_UTF8_VALUE);

    }

    /**
     * 获取当前的请求路径
     *
     * @return
     */
    public static String getCurrentURL() {
        return getRequest().getRequestURI();
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }

    /**
     * 获取session
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 使用RequestContextHolder获取当前请求上下文
     *
     * @return
     */
    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }


}
